/**
 *流量表历史记录
 */
'use strict';

const conn = require('../../libs/DB/Conn');
const _ = require("underscore");
const decimal = require("decimal");
const moment = require("moment");
const {timeComponent,chartDataProcessing} = require("../../libs/Utils")
const columnNameObj = require("./deviceChartConfig").chart.flowMeter;
const deviceType = require("./deviceChartConfig").type.flowMeter;

module.exports = async function (params) {
    try {
        let timeInterval = timeComponent(params.startTime,params.endTime,params.type);
        let sql = `SELECT
        dd.device_no AS deviceNo,
        DATE_FORMAT(dd.data_time,"%Y-%m-%d %H:%i:%s") AS dataTime,
        ${timeInterval.queryGroupTime} 
        df.device_name AS deviceName,
        dd.instantaneous_flow AS instantaneousFlow,
        dd.instantaneous_flow_unit AS instantaneousFlowUnit,
        dd.accumulated_flow AS accumulatedFlow,
        dd.accumulated_flow_unit AS accumulatedFlowUnit,
        dd.accumulated_flow_consumption AS accumulatedFlowConsumption,
        dd.positive_accumulated_flow AS positiveAccumulatedFlow,
        dd.positive_accumulated_flow_unit AS positiveAccumulatedFlowUnit,
        dd.negative_accumulated_flow AS negativeAccumulatedFlow,
        dd.negative_accumulated_flow_unit AS negativeAccumulatedFlowUnit,
        dd.temperature,
        dd.pressure,
        dd.frequency,
        dd.pressure_delta AS pressureDelta,
        dd.density,
        dd.power_outage_duration AS powerOutageDuration,
        dd.power_outage_count AS powerOutageCount,
        rf.range_name AS rangeName
    FROM
    data_flow_meter_${params.userDomainId} dd
    INNER JOIN device_file df ON df.device_no = dd.device_no
    AND df.delete_sign = 1 AND df.device_type = ${deviceType} 
    AND df.range_id IN (?)
    INNER JOIN range_file rf ON df.range_id = rf.range_id AND rf.delete_sign = 1 
    WHERE 1 = 1 ${timeInterval.startTime && timeInterval.endTime ? ` AND (dd.data_time > "${timeInterval.startTime}" AND dd.data_time <= "${timeInterval.endTime}")` : `` } 
    ORDER BY dd.data_time DESC`;
        let flowMeterDataList = await conn(sql,[params.rangeIds]);
        let flowMeterDataGroup = _.groupBy(flowMeterDataList,"deviceNo");
        let dataList = [];
        for(const deviceNo in flowMeterDataGroup){
            let deviceDataList = flowMeterDataGroup[deviceNo];
            let deviceObj = {
                deviceName:deviceDataList[0].deviceName,
                rangeName:deviceDataList[0].rangeName,
                deviceNo:deviceNo,
                instantaneousFlow:deviceDataList[0].instantaneousFlow,
                instantaneousFlowUnit:deviceDataList[0].instantaneousFlowUnit,
                accumulatedFlow:deviceDataList[0].accumulatedFlow,
                accumulatedFlowUnit:deviceDataList[0].accumulatedFlowUnit,
                accumulatedFlowConsumption:0,
                positiveAccumulatedFlow:deviceDataList[0].positiveAccumulatedFlow,
                positiveAccumulatedFlowUnit:deviceDataList[0].positiveAccumulatedFlowUnit,
                negativeAccumulatedFlow:deviceDataList[0].negativeAccumulatedFlow,
                negativeAccumulatedFlowUnit:deviceDataList[0].negativeAccumulatedFlowUnit,
                temperature : deviceDataList[0].temperature,
                pressure:deviceDataList[0].pressure,
                frequency:deviceDataList[0].frequency,
                pressureDelta:deviceDataList[0].pressureDelta,
                density:deviceDataList[0].density,
                power_outage_duration:"00:00:00",
                power_outage_count:0,
                dataList:[],
            }
            deviceDataList.forEach(function (data){
                let total = moment.duration(deviceDataList[0].powerOutageDuration).add(moment.duration(data.powerOutageDuration));
                deviceObj.powerOutageDuration =  moment.utc(total.asMilliseconds()).format('HH:mm:ss')
                deviceObj.powerOutageCount =  decimal.add(deviceObj.powerOutageCount,data.powerOutageCount).internal
                deviceObj.accumulatedFlowConsumption =  decimal.add(deviceObj.accumulatedFlowConsumption,data.accumulatedFlowConsumption).internal
            })
            if(params.type === "hour"){
                deviceObj.dataList = deviceDataList
            }else {
                let timeGroup = _.groupBy(deviceDataList,"groupTime");
                for(const time in timeGroup){
                    let timeGroupList = timeGroup[time];
                    let deviceDataObj = {
                        dataTime:time,
                        dataCreateTime:timeGroupList[timeGroupList.length - 1].dataTime,
                        instantaneousFlow:deviceDataList[0].instantaneousFlow,
                        instantaneousFlowUnit:deviceDataList[0].instantaneousFlowUnit,
                        accumulatedFlow:deviceDataList[0].accumulatedFlow,
                        accumulatedFlowUnit:deviceDataList[0].accumulatedFlowUnit,
                        accumulatedFlowConsumption:0,
                        positiveAccumulatedFlow:deviceDataList[0].positiveAccumulatedFlow,
                        positiveAccumulatedFlowUnit:deviceDataList[0].positiveAccumulatedFlowUnit,
                        negativeAccumulatedFlow:deviceDataList[0].negativeAccumulatedFlow,
                        negativeAccumulatedFlowUnit:deviceDataList[0].negativeAccumulatedFlowUnit,
                        temperature : deviceDataList[0].temperature,
                        pressure:deviceDataList[0].pressure,
                        frequency:deviceDataList[0].frequency,
                        pressureDelta:deviceDataList[0].pressureDelta,
                        density:deviceDataList[0].density,
                        powerOutageDuration:"00:00:00",
                        powerOutageCount:0,
                    }
                    deviceDataList.forEach(function (data){
                        let total = moment.duration(deviceDataObj.powerOutageDuration).add(moment.duration(data));
                        deviceDataObj.powerOutageDuration =  moment.utc(total.asMilliseconds()).format('HH:mm:ss');
                        deviceDataObj.powerOutageCount =  decimal.add(deviceDataObj.powerOutageCount,data.powerOutageCount).internal;
                        deviceDataObj.accumulatedFlowConsumption =  decimal.add(deviceDataObj.accumulatedFlowConsumption,data.accumulatedFlowConsumption).internal;
                    })
                    deviceObj.dataList.push(deviceDataObj);
                }
            }
            deviceObj.chart = chartDataProcessing(deviceObj.dataList,columnNameObj);
            dataList.push(deviceObj);
        }

        return { success: true,dataList:dataList};
    }catch (e){
        return { success: false,dataList:[],message:e.code === "ER_NO_SUCH_TABLE" ? "当前账号无此类设备" : e.sqlMessage};
    }
};